package com.freemyleft.left.zapp.selectimage.activity;


import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bm.library.PhotoView;
import com.freemyleft.left.R;
import com.freemyleft.left.zapp.selectimage.BitmapUtils;
import com.freemyleft.left.zapp.selectimage.FileUtils;
import com.freemyleft.left.zapp.selectimage.PhotoZoomUtils;
import com.freemyleft.left.zapp.selectimage.PicassoUtils;
import com.freemyleft.left.zapp.selectimage.SystemPhotoUtils;
import com.freemyleft.left.zapp.selectimage.adapter.ZhyCommonAdapter;
import com.freemyleft.left.zapp.selectimage.adapter.ZhyViewHolder;
import com.freemyleft.left.zapp.selectimage.bean.Folder;
import com.freemyleft.left.zapp.selectimage.bean.Image;
import com.freemyleft.left.zapp.selectimage.listener.CameraListener;
import com.freemyleft.left.zapp.selectimage.listener.SelectImageFinishListener;


import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ImageSelectPhotoActivity extends FragmentActivity {

    private GridView mGrid;
    private PhotoView mPerviewImage;
    private RelativeLayout mPerview;
    private ImageView mReturn;
    private TextView mFinish;
    private LinearLayout mClassify;
    private ListView mListClassify;
    private LinearLayout mBottom;
    private View mHideClassify;
    private TextView mBottomName;
    private String mImageName;

    private int mSelectImageCount;
    private Activity mActivity;
    private boolean mIsClassifyShow = false;

    // 文件夹数据
    private List<Folder> mFolderList = new ArrayList<>();
    private List<Image> mImageList = new ArrayList<>();
    private ZhyCommonAdapter<Image> mAdapter = null;
    private Map<String, Image> mImageMap = new HashMap<>();
    private ZhyCommonAdapter<Folder> mFolderAdapter = null;
    private ViewPager viewPager = null;
    private static SelectImageFinishListener mSelectImageFinishListener;
    private static CameraListener mCameraListener;
    private boolean mIsSingleClip = false;
    private String mSelectClassifyIndex = "";
    private int mCutWidth = 0;
    private int mCutHight = 0;
    private final int ZOOM = 1000;
    private File mPhotoFile;
    private Uri mUri;
    private ConvenientBanner banner;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_select_photo);
        initLayout();
        initView();
    }

    public static void setSelectImageFinishListener(SelectImageFinishListener listener) {
        mSelectImageFinishListener = listener;
    }

    public static void setCameraListener(CameraListener listener) {
        mCameraListener = listener;
    }

    private void initLayout() {
        mActivity = ImageSelectPhotoActivity.this;
        mImageName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        mPhotoFile = new File(Environment.getExternalStorageDirectory(), mImageName);
        mSelectImageCount = getIntent().getIntExtra("count", 9);
        mIsSingleClip = getIntent().getBooleanExtra("is_clip", false);
        mCutWidth = getIntent().getIntExtra("cut_width", 300);
        mCutHight = getIntent().getIntExtra("cut_hight", 300);
        banner = (ConvenientBanner) findViewById(R.id.banner);
        mGrid = (GridView) findViewById(R.id.m_grid);
        mPerviewImage = (PhotoView) findViewById(R.id.m_perview_image);
        mPerview = (RelativeLayout) findViewById(R.id.m_perview);
        mReturn = (ImageView) findViewById(R.id.m_return);
        mFinish = (TextView) findViewById(R.id.m_finish);
        mClassify = (LinearLayout) findViewById(R.id.m_classify);
        mListClassify = (ListView) findViewById(R.id.m_list_classify);
        mBottom = (LinearLayout) findViewById(R.id.m_bottom);
        mHideClassify = findViewById(R.id.m_hide_classify);
        mBottomName = (TextView) findViewById(R.id.m_bottom_name);
        mHideClassify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeClassify();
            }
        });
        mBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mClassify.setVisibility(View.VISIBLE);
                int[] bottomLocation = new int[2];
                mBottom.getLocationInWindow(bottomLocation);
                if (!mIsClassifyShow) {
                    ObjectAnimator.ofFloat(mClassify, "translationY", bottomLocation[1], 0).setDuration(500).start();
                    mIsClassifyShow = true;
                    if (mFolderAdapter != null) {
                        mFolderAdapter.notifyDataSetChanged();
                        return;
                    }
                    showFolderData();
                } else {
                    closeClassify();
                }
            }
        });
        mReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Image> list = new ArrayList<Image>();
                for (String str : mImageMap.keySet()) {
                    list.add(mImageMap.get(str));
                }
                if (list.size() == 1 && mIsSingleClip && mCameraListener != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        mUri = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".fileprovider", new File(list.get(0).path));
                    } else {
                        mUri = Uri.fromFile(new File(list.get(0).path));
                    }
                    PhotoZoomUtils.startPhotoZoom(ImageSelectPhotoActivity.this, mUri, mPhotoFile, mCutWidth, mCutHight, ZOOM);
                } else if (mSelectImageFinishListener != null) {
                    mSelectImageFinishListener.selectImageFinish(list);
                    finish();
                }
//                finish();
            }
        });
    }

    private void showFolderData() {
        mFolderAdapter = new ZhyCommonAdapter<Folder>(mActivity, mFolderList, R.layout.item_classify_photo) {
            @Override
            public void convert(ZhyViewHolder holder, final Folder item, int position) {
                PicassoUtils.picasso(mActivity, item.cover.path, 300, 300, (ImageView) holder.getView(R.id.m_image));
                holder.setText(R.id.m_name, item.name);
                ImageView select = holder.getView(R.id.m_select);
                select.setVisibility(mSelectClassifyIndex.equals(item.path) ? View.VISIBLE : View.GONE);
                holder.getView(R.id.m_click).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBottomName.setText(item.name);
                        mSelectClassifyIndex = item.path;
                        mImageList.clear();
                        mImageList.addAll(item.images);
                        mAdapter.notifyDataSetChanged();
                        mFolderAdapter.notifyDataSetChanged();
                        closeClassify();
                    }
                });
            }
        };
        mListClassify.setAdapter(mFolderAdapter);
    }

    private void closeClassify() {
        int[] bottomLocation = new int[2];
        mBottom.getLocationInWindow(bottomLocation);
        ObjectAnimator.ofFloat(mClassify, "translationY", 0, bottomLocation[1]).setDuration(500).start();
        mIsClassifyShow = false;
    }

    public void initView() {
        SystemPhotoUtils spu = new SystemPhotoUtils(mActivity);
        spu.setOnUpdataDataListener(new SystemPhotoUtils.OnUpdataDataListener() {
            @Override
            public void updateData(List<Folder> folderList, List<Image> imagelist) {
                mImageList.clear();
                mFolderList.clear();
                mImageList = imagelist;
                Folder folder = new Folder();
                folder.name = "所有图片";
                folder.path = "";
                if (imagelist.size() != 0) {
                    folder.cover = imagelist.get(0);
                }
                folder.images.addAll(imagelist);
                mFolderList.add(folder);
                mFolderList.addAll(folderList);
                showData();
            }
        });
    }

    private void showData() {
        mAdapter = new ZhyCommonAdapter<Image>(mActivity, mImageList, R.layout.item_select_photo) {
            @Override
            public void convert(ZhyViewHolder holder, final Image item, final int position) {
                ImageView imageView = (ImageView) holder.getView(R.id.m_image);
                ImageView select = holder.getView(R.id.m_select);
                PicassoUtils.picasso(mActivity, item.path, 300, 300, imageView);
                select.setImageResource(item.isSelect ? R.mipmap.btn_selected : R.mipmap.btn_unselected);
                if (mIsSelectFinish) {
                    select.setVisibility(item.isSelect ? View.VISIBLE : View.GONE);
                } else {
                    select.setVisibility(View.VISIBLE);
                }
                select.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        item.isSelect = !item.isSelect;
                        if (item.isSelect) {
                            mImageMap.put(item.path, item);
                        } else {
                            mImageMap.remove(item.path);
                        }
                        finishListener();
                        mAdapter.notifyDataSetChanged();
                    }
                });
                imageView.setOnClickListener(new View.OnClickListener() {

                    private int height;
                    private int width;

                    @Override
                    public void onClick(View v) {
                        if (mAdapter.getCount() == 1) {
                            mPerview.setVisibility(View.VISIBLE);
                            mBottom.setVisibility(View.GONE);
                            width = item.width != 0 ? item.width : BitmapUtils.getScreenWidth(mActivity);
                            height = item.height != 0 ? item.height : BitmapUtils.getScreenHight(mActivity);
                            try {
                                //imageView.setMaxScale(10);
                                mPerviewImage.enable();
                                mPerviewImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                // 设置动画的插入器
                                mPerviewImage.setInterpolator(new AccelerateDecelerateInterpolator());
                                PicassoUtils.picasso(mActivity, item.path, width, height, mPerviewImage);
                            } catch (Exception e) {

                            }
                        } else {
                            Intent intent = new Intent(ImageSelectPhotoActivity.this, ImageShowActivity.class);
                            intent.putExtra("images", (Serializable) mImageList);
                            intent.putExtra("position" ,position);
                            startActivity(intent);


                        }
                    }
                });

            }
        };
        mGrid.setAdapter(mAdapter);
    }

    private boolean mIsSelectFinish = false;

    private void finishListener() {
        mFinish.setText("完成(" + mImageMap.size() + "/" + mSelectImageCount + ")");
        mFinish.setEnabled(mImageMap.size() > 0 ? true : false);
        mIsSelectFinish = mImageMap.size() == mSelectImageCount ? true : false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == ZOOM) {//裁剪
            Image image = FileUtils.getImage(mActivity, mPhotoFile.getPath(), mImageName);
            if (mCameraListener != null) {
                mCameraListener.cameraListener(image);
                finish();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mPerview.getVisibility() == View.VISIBLE) {
                mPerview.setVisibility(View.GONE);
                mBottom.setVisibility(View.VISIBLE);
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
